<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <!-- 搜索区域 -->
      <a-form layout="inline">
        <a-row :gutter="24">
          <a-col :md="10" :sm="12">
            <a-form-item label="用户账号" style="margin-left:8px">
              <a-input placeholder="请输入账号" v-model.trim="queryParam.username"></a-input>
            </a-form-item>
          </a-col>
          <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
            <a-col :md="6" :sm="24">
              <a-button type="primary" @click="searchQuery" icon="search" style="margin-left: 18px">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
            </a-col>
          </span>
        </a-row>
      </a-form>
    </div>
    <!-- 操作按钮区域 -->
    <div class="table-operator" :md="24" :sm="24">
      <a-button @click="handleAdd" type="primary" icon="plus" style="margin-top: 16px">新建用户</a-button>
      <a-button type="primary" @click="onStatusChange(1)">批量启用</a-button>
      <a-button style="background: orange; color: #fff;" @click="onStatusChange(2)">批量禁用</a-button>

      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel">
            <a-icon type="delete"/>
            取消关联
          </a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作
          <a-icon type="down"/>
        </a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{
        selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        @change="handleTableChange">
        <!-- 主账号禁止操作 -->
        <template slot="statusSlot" slot-scope="text, record">
          <a-switch :checked="text === 1 ? true :false" @change="handleChange(record.id, text === 1 ? 2 : 1)" :disabled="record.isAdmin === 'Y'" />
        </template>

        <span slot="action" slot-scope="text, record">
          <!-- 主账号禁止操作 -->
          <a @click="handleEdit(record)" v-if="record.isAdmin != 'Y'">编辑</a>
          <a-divider type="vertical" v-if="record.isAdmin != 'Y'"/>

          <a-dropdown>
            <a class="ant-dropdown-link">
              更多 <a-icon type="down"/>
            </a>
            <a-menu slot="overlay">
<!--              <a-menu-item>-->
<!--                <a href="javascript:;" @click="handleDeptRole(record)">部门角色</a>-->
<!--              </a-menu-item>-->

              <a-menu-item>
                <a @click="handleCategoryGroup(record)">类目组</a>
              </a-menu-item>

              <a-menu-item>
                <a @click="handleDetail(record)">用户详情</a>
              </a-menu-item>

              <!-- 主账号禁止操作 -->
              <a-menu-item v-if="record.isAdmin != 'Y'">
                <a-popconfirm title="确定取消与选中部门关联吗?" @confirm="() => handleDelete(record.id)">
                  <a>取消关联</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>

      </a-table>
    </div>
    <!-- table区域-end -->

    <!-- 表单区域 -->
    <user-modal ref="modalForm" @ok="modalFormOk" :rolesOptions="rolesOptions"></user-modal>
    <dept-role-user-modal ref="deptRoleUser"></dept-role-user-modal>
    <!-- 类目组 -->
    <category-group-modal ref="categoryGroupModal" @ok="modalFormOk"></category-group-modal>
  </a-card>
</template>

<script>
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import { deleteAction } from '@/api/manage'
  import UserModal from './UserModal'
  import DeptRoleUserModal from './DeptRoleUserModal'
  import { frozenBatch, queryall } from '@/api/api'
  import CategoryGroupModal from '@/views/system/modules/CategoryGroupModal'

  export default {
    name: "DeptUserInfo",
    mixins: [JeecgListMixin],
    components: {
      DeptRoleUserModal,
      UserModal,
      CategoryGroupModal
    },
    data() {
      return {
        description: '用户信息',
        currentDept: {},
        // 表头
        columns: [
          {
            title: '用户账号',
            align: "center",
            dataIndex: 'username'
          },
          {
            title: '部门',
            align: "center",
            dataIndex: 'departFullName'
          },
          {
            title: '启用状态',
            align: "center",
            dataIndex: 'status',
            scopedSlots: {customRender: 'statusSlot'},
          },
          // {
          //   title: '性别',
          //   align: "center",
          //   dataIndex: 'sex_dictText'
          // },
          {
            title: '电话',
            align: "center",
            dataIndex: 'phone'
          },
          {
            title: '操作',
            dataIndex: 'action',
            scopedSlots: {customRender: 'action'},
            align: "center",
            width: 150
          }
        ],
        url: {
          list: "/sys/user/list",
          edit: "/sys/user/editSysDepartWithUser",
          delete: "/sys/user/deleteUserInDepart",
          deleteBatch: "/sys/user/deleteUserInDepartBatch",
        },
        disableMixinCreated: true,
        rolesOptions: []
      }
    },
    created(){
      this.initRoleList();
    },
    methods: {
      //初始化角色字典
      initRoleList() {
        queryall().then((res) => {
          if (res.success) {
            this.rolesOptions = res.result.map(item => {
              return {
                text : item.roleName,
                value: item.id
              }
            })
          }else{
            this.$message.warning(res.message);
          }
        })
      },
      batchDel: function () {
        if (!this.url.deleteBatch) {
          this.$message.error("请设置url.deleteBatch属性!")
          return
        }
        if (!this.currentDept.id) {
          this.$message.error("未选中任何部门，无法取消部门与用户的关联!")
          return
        }
        if (this.selectedRowKeys.length <= 0) {
          this.$message.warning('请选择一条记录！');
          return;
        } else {
          var ids = "";
          for (var a = 0; a < this.selectedRowKeys.length; a++) {
            ids += this.selectedRowKeys[a] + ",";
          }
          var that = this;
          that.$confirm({
            title: "确认取消",
            content: "是否取消用户与选中部门的关联?",
            onOk: function () {
              deleteAction(that.url.deleteBatch, {depId: that.currentDept.id, userIds: ids}).then((res) => {
                if (res.success) {
                  that.$message.success("删除用户与选中部门关系成功！");
                  that.loadData();
                  that.onClearSelected();
                } else {
                  that.$message.warning(res.message);
                }
              });
            }
          });
        }
      },
      handleDelete: function (id) {
        if (!this.url.delete) {
          this.$message.error("请设置url.delete属性!")
          return
        }
        if (!this.currentDept.id) {
          this.$message.error("未选中任何部门，无法取消部门与用户的关联!")
          return
        }
        var that = this;
        deleteAction(that.url.delete, {depId: this.currentDept.id, userId: id}).then((res) => {
          if (res.success) {
            that.$message.success(res.message);
            that.loadData();
          } else {
            that.$message.warning(res.message);
          }
        });
      },
      open(record) {
        this.currentDept = record;
        this.queryParam.orgCode = record.orgCode;
        this.loadData(1);
      },
      handleEdit: function (record) {
        this.$refs.modalForm.title = "编辑";
        this.$refs.modalForm.disableSubmit = false;
        this.$refs.modalForm.edit({...record});
      },
      handleDetail(record){
        this.$refs.modalForm.title = "详情";
        this.$refs.modalForm.disableSubmit = true;
        this.$refs.modalForm.edit({...record});
      },
      handleAdd: function () {
        if (!this.currentDept.id) {
          this.$message.error("请选择一个部门!")
        } else {
          //初始化负责部门
          this.$refs.modalForm.title = "新增";
          this.$refs.modalForm.disableSubmit = false;
          this.$refs.modalForm.edit({selecteddeparts: this.currentDept.id, orgCode: this.currentDept.orgCode});
        }
      },
      handleDeptRole(record){
        if(this.currentDept.id){
          this.$refs.deptRoleUser.add(record,this.currentDept.id);
          this.$refs.deptRoleUser.title = "部门角色分配";
        }else{
          this.$message.warning("请先选择一个部门!");
        }
      },
      onStatusChange(status){
        if (!this.currentDept.id) {
          this.$message.error("请先选择一个部门!")
          return
        }
        if(!(this.selectedRowKeys && this.selectedRowKeys.length)){
          this.$message.warning('请选择数据');
          return;
        }
        this.handleChange(this.selectedRowKeys.join(','), status);
      },
      handleChange(ids, status){
        let that = this;
        if(status === 2){
          that.$confirm({
            title:'账号冻结',
            content: (
              <div>
                <div style="color: red">冻结后将无法登陆本系统</div>
                <div>你还要继续吗？</div>
              </div>
            ),
            okText: '继 续',
            onOk() {
              that.handlePost(ids, status);
            },
            onCancel() {  },
          });
        }else{
          that.handlePost(ids, status);
        }
      },
      handlePost(ids, status){
        frozenBatch({ ids, status }).then((res) => {
          if (res.success) {
            this.$message.success(res.message);
            this.loadData();
            this.onClearSelected();
          } else {
            this.$message.warning(res.message);
          }
        });
      },
      onSelectChange(selectedRowKeys, selectionRows) {
        let flag = selectionRows.some(item => item.isAdmin === 'Y');
        if(flag){
          this.$message.warning('存在主账号，不允许操作');
          return;
        }
        this.selectedRowKeys = selectedRowKeys;
        this.selectionRows = selectionRows;
      },
      searchReset() {
        this.queryParam = {
          depId: this.currentDept.id
        }
        this.loadData(1);
      },
      handleCategoryGroup(record){
        this.$refs.categoryGroupModal.show(record.username);
        this.$refs.categoryGroupModal.title = "类目组选择";
      }
    }
  }
</script>
<style scoped>
</style>